package com.hjz.hongbaotest.wxapi;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.hjz.hongbaotest.utils.Constants;
import com.hjz.hongbaotest.activity.MainActivity;
import com.hjz.hongbaotest.utils.Md5Tool;
import com.hjz.hongbaotest.R;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.tencent.mm.opensdk.modelbase.BaseReq;
import com.tencent.mm.opensdk.modelbase.BaseResp;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.IWXAPIEventHandler;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Random;

/**
 * ************************************************************
 * 类描述：
 * 作者：Administrator
 * 创建时间：2017-10-11 11:10
 * <p>
 * ************************************************************
 */

public class WXEntryActivity extends AppCompatActivity implements IWXAPIEventHandler {

    private IWXAPI api; // IWXAPI 是第三方app和微信通信的openapi接口

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.login_layout);
        //注册api
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID);
        api.handleIntent(getIntent(), this);
    }

    @Override
    public void onReq(BaseReq baseReq) {

    }

    /**
     * 发送微信授权请求的响应结果
     *
     * @param baseResp
     */
    @Override
    public void onResp(BaseResp baseResp) {

        switch (baseResp.errCode) {
            //如果errcode为零，表示用户同意授权
            case BaseResp.ErrCode.ERR_OK:
                // 得到所需的code
                //此处报错检查下载的sdk是否正确
                String code = ((SendAuth.Resp) baseResp).code;

                Log.i("wxentry", "code = " + code);
                // 获取code之后携带参数获取用户信息
                getToken(code);
                break;

            default:
                break;
        }
    }

    /**
     * 携带参数获取用户信息
     *
     * @param code
     */
    private void getToken(String code) {

        OkGo.<String>get(Constants.OAUTH)
                .params("appid", Constants.APP_ID)
                .params("secret", Constants.SECRET)
                .params("code", code)
                .params("grant_type", "authorization_code")//固定写法
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {

                        String access_token = "";//接口调用凭证。
                        String expires_in = "";//接口调用凭证超时时间，单位（秒）。
                        String refresh_token = "";//用户刷新access_token。
                        String openid = "";//授权用户唯一标识。
                        String scope = "";//用户授权的作用域，使用逗号（,）分隔
                        String unionid = "";//当且仅当该网站应用已获得该用户的userinfo授权时，才会出现该字段。
                        String result = response.body();
                        // 解析数据，获取用户信息
                        try {
                            JSONObject job = new JSONObject(result);
                            access_token = job.getString("access_token");
                            expires_in = job.getString("expires_in");
                            refresh_token = job.getString("refresh_token");
                            openid = job.getString("openid");
                            scope = job.getString("scope");
                            unionid = job.getString("unionid");
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                        // 判断openid是否为空
                        if (!openid.equals("")) {
                            Log.i("wxentry", access_token + "---" + openid + "---" + expires_in + "---" + refresh_token + "---" + scope + "---" + unionid);

                            //这个位置调用后台给的登录接口，别忘了登录成功之后finish()当前activity，不然会停留在空白页
                            //传参给后台，获取返回的token，UID并保存
                            setLogin(access_token, openid);
                        } else {
                            Log.i("wxentry", "检查appsecret码是否重置");
                            //销毁界面
                            finish();
                        }
                    }
                });
    }

    /**
     * 授权成功，获取用户信息
     *
     * @param access_token
     * @param openid
     */
    private void setLogin(String access_token, String openid) {

        OkGo.<String>post(Constants.USERINFO)
                .params("access_token", access_token)
                .params("openid", openid)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String openid = "";
                        String nickname = "";//昵称
                        String headimgurl = "";//头像路径

                        String result = response.body();

                        try {
                            JSONObject object = new JSONObject(result);
                            openid = object.getString("openid");
                            nickname = object.getString("nickname");
                            headimgurl = object.getString("headimgurl");

                            Log.e("----headimgurl---",headimgurl);
                            Log.e("----nickname---",nickname);

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        // 执行联网方法，将数据传给服务器
                        skip(openid,nickname);
                    }
                });
    }

    /**
     * 联网上传用户信息
     */
    private void skip(String openid,final String nickname) {


        String rdm=getStringRandom(6);
        Md5Tool tool = new Md5Tool();

        String auth=tool.getMD5Str(openid + rdm);

        OkGo.<String>post("http://192.168.1.133:8080/redmap/openLogin.shtml")
                .params("openid", openid)
                .params("rdm", rdm)
                .params("auth",auth)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        String result = response.body();

                        try {
                            Log.i("wxentry","result"+result);
                            JSONObject object = new JSONObject(result);

                            // 如果获取成功
                                String sessionId = object.getString("sessionId");

                                //偏好设置保存user_id
                                SharedPreferences.Editor editor =getSharedPreferences("user",MODE_PRIVATE).edit();//文件名为user
                                 editor.putString("name",nickname);
                                 editor.putString("sessionId",sessionId);
                                editor.commit();//提交

                                Toast.makeText(WXEntryActivity.this,object.getString("msg"),Toast.LENGTH_SHORT).show();
                                //跳转界面
                                startActivity(new Intent(WXEntryActivity.this,MainActivity.class));
                                //销毁当前Activity
                                finish();

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }
                });

    }

    //生成随机数字和字母,
    public String getStringRandom(int length) {

        String val = "";
        Random random = new Random();

        //参数length，表示生成几位随机数
        for(int i = 0; i < length; i++) {

            String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
            //输出字母还是数字
            if( "char".equalsIgnoreCase(charOrNum) ) {
                //输出是大写字母还是小写字母
                int temp = random.nextInt(2) % 2 == 0 ? 65 : 97;
                val += (char)(random.nextInt(26) + temp);
            } else if( "num".equalsIgnoreCase(charOrNum) ) {
                val += String.valueOf(random.nextInt(10));
            }
        }
        return val;
    }
}